import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Typography,
  Tag,
  Tooltip,
  message,
  Row,
  Col,
  Divider,
  Select,
  Input,
  Descriptions,
  Spin,
  Transfer,
} from 'antd';
import {
  KeyOutlined,
  TeamOutlined,
  ReloadOutlined,
  EditOutlined,
  EyeOutlined,
  PlusOutlined,
  SearchOutlined,
  SafetyOutlined,
} from '@ant-design/icons';
import { usePlatformPermission } from '../../hooks/platform/usePlatformPermission';
import { usePlatformPermissions, useMenuGroups } from '../../hooks/business/usePlatformPermissions';
import { platformPermissionApi } from '../../services/platform/api';
import { useAsyncState } from '../../hooks/common/useErrorHandler';
import type { PlatformRole } from '../../types/platform';

const { Title, Text } = Typography;
const { Search } = Input;

// 菜单分组配置
const MENU_GROUPS = {
  'dashboard': { label: '仪表盘', color: 'blue' },
  'tenant': { label: '租户管理', color: 'green' },
  'user': { label: '用户管理', color: 'orange' },
  'system': { label: '系统管理', color: 'purple' },
  'monitor': { label: '监控管理', color: 'red' },
};

interface MenuData {
  key: string;
  title: string;
  description: string;
  icon?: string;
  order?: number;
  hidden?: boolean;
  requiredPermissions?: string[];
}

const PlatformPermissionsPage: React.FC = () => {
  // 使用统一的异步状态管理
  const { executeAsync, hasAnyLoading, hasError, error, clearError } = useAsyncState();

  // 数据状态
  const [roles, setRoles] = useState<PlatformRole[]>([]);
  const [menus, setMenus] = useState<MenuData[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState('');

  // 本地UI状态
  const [modalVisible, setModalVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<PlatformRole | null>(null);
  const [detailRole, setDetailRole] = useState<PlatformRole | null>(null);
  const [modalLoading, setModalLoading] = useState(false);
  const [selectedMenus, setSelectedMenus] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  
  const { isSuperAdmin } = usePlatformPermission();

  // 统一错误处理
  useEffect(() => {
    if (hasError && error) {
      message.error(error.message || '操作失败');
      clearError();
    }
  }, [hasError, error, clearError]);

  // 获取菜单数据
  const loadMenus = async () => {
    return executeAsync('loadMenus', async () => {
      const response = await platformPermissionApi.getAllMenus();
      const menuData = response.map((menu: any) => ({
        key: menu.key,
        title: menu.label,
        description: menu.path || '',
        icon: menu.icon,
        order: menu.order,
        hidden: menu.hidden,
        requiredPermissions: menu.requiredPermissions
      }));
      setMenus(menuData);
      return menuData;
    });
  };

  // 获取角色数据
  const loadRoles = async () => {
    return executeAsync('loadRoles', async () => {
      const response = await platformPermissionApi.getRolesWithMenusPage({
        current: pagination.current,
        size: pagination.pageSize,
        search: searchText,
      });
      
      const rolesData = response.records || [];
      setRoles(rolesData);
      setPagination(prev => ({
        ...prev,
        total: response.totalElements || 0,
      }));
      
      return rolesData;
    });
  };

  // 获取角色菜单权限
  const getRoleMenus = async (roleCode: string): Promise<string[] | null> => {
    return executeAsync('getRoleMenus', async () => {
      const response = await platformPermissionApi.getRoleMenuCodes(roleCode);
      return response || [];
    });
  };

  // 更新角色权限
  const updateRolePermissions = async (roleCode: string, menuCodes: string[]) => {
    return executeAsync('updateRolePermissions', async () => {
      await platformPermissionApi.assignMenusToRole(roleCode, menuCodes);
      message.success('权限更新成功');
      await loadRoles(); // 重新加载数据
    });
  };

  // 初始化数据加载
  useEffect(() => {
    loadMenus();
    loadRoles();
  }, []);

  // 监听搜索和分页变化
  useEffect(() => {
    loadRoles();
  }, [pagination.current, pagination.pageSize, searchText]);

  // 刷新数据
  const handleRefresh = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    loadRoles();
    loadMenus();
  };

  // 处理分页变化
  const handleTableChange = (page: number, pageSize?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 打开新增/编辑模态框
  const openModal = async (role?: PlatformRole) => {
    setEditingRole(role || null);
    let menuPermissions: string[] = [];
    if (role) {
      try {
        const result = await getRoleMenus(role.code);
        menuPermissions = result || [];
      } catch (error) {
        message.error('获取角色菜单失败');
        return;
      }
    }
    setSelectedMenus(menuPermissions);
    if (role) {
      form.setFieldsValue({
        code: role.code,
        name: role.name,
        menus: menuPermissions,
      });
    } else {
      form.resetFields();
    }
    setModalVisible(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setModalVisible(false);
    setEditingRole(null);
    setSelectedMenus([]);
    form.resetFields();
  };

  // 保存角色菜单权限
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setModalLoading(true);
      
      if (editingRole) {
        await updateRolePermissions(editingRole.code, values.menus || []);
        closeModal();
      }
    } catch (error) {
      console.error('更新失败:', error);
      message.error('更新失败');
    } finally {
      setModalLoading(false);
    }
  };

  // 查看详情
  const handleDetail = (role: PlatformRole) => {
    setDetailRole(role);
    setDetailVisible(true);
  };

  // 获取菜单分组
  const getMenusByGroup = () => {
    const groups: Record<string, MenuData[]> = {};
    menus.forEach(menu => {
      let category = 'other';
      if (menu.description.includes('/dashboard')) category = 'dashboard';
      else if (menu.description.includes('/tenant')) category = 'tenant';
      else if (menu.description.includes('/user') || menu.description.includes('/role') || menu.description.includes('/permission')) category = 'user';
      else if (menu.description.includes('/system') || menu.description.includes('/setting')) category = 'system';
      else if (menu.description.includes('/ticket')) category = 'monitor';
      
      if (!groups[category]) {
        groups[category] = [];
      }
      groups[category].push(menu);
    });
    return groups;
  };

  // 移除客户端过滤，改为服务端分页查询

  // 表格列定义
  const columns = [
    {
      title: '角色信息',
      key: 'roleInfo',
      render: (_: any, record: PlatformRole) => (
        <Space direction="vertical" size={4}>
          <Space>
            <TeamOutlined style={{ color: '#1890ff' }} />
            <Text strong>{record.name}</Text>
            {record.isBuiltin && <Tag color="gold">内置</Tag>}
            {record.status === 'active' || record.status === 1 ? 
              <Tag color="green">启用</Tag> : 
              <Tag color="red">禁用</Tag>
            }
          </Space>
          <Text code style={{ fontSize: 12 }}>{record.code}</Text>
          {record.description && (
            <Text type="secondary" style={{ fontSize: 12 }}>
              {record.description}
            </Text>
          )}
        </Space>
      ),
    },
    {
      title: '菜单数量',
      dataIndex: 'permissions',
      key: 'permissions',
      width: 100,
      render: (permissions: string[]) => (
        <Tag color="blue">{permissions?.length || 0} 个菜单</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (createTime: string) => (
        <Text style={{ fontSize: 12 }}>
          {createTime ? new Date(createTime).toLocaleDateString('zh-CN') : '-'}
        </Text>
      ),
    },

    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: PlatformRole) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleDetail(record)}
            style={{ color: '#1890ff' }}
          >
            详情
          </Button>
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={async () => await openModal(record)}
            disabled={record.isBuiltin && !isSuperAdmin}
            style={{ color: '#52c41a' }}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 页面标题和操作区 */}
      <div style={{ 
        marginBottom: 24, 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        padding: '0 4px'
      }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <KeyOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            权限管理
          </Title>
          <Text type="secondary" style={{ fontSize: 14, marginTop: 4, display: 'block' }}>
            管理平台角色和菜单分配
          </Text>
        </div>
        <Space>
          <Search
            placeholder="搜索角色名称或编码"
            allowClear
            style={{ width: 240 }}
            onSearch={handleSearch}
            prefix={<SearchOutlined />}
          />
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            style={{
              borderColor: '#d9d9d9',
              color: '#666'
            }}
          >
            刷新
          </Button>

        </Space>
      </div>

      {/* 角色表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={hasAnyLoading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50'],
            onChange: handleTableChange,
            onShowSizeChange: handleTableChange,
          }}
          size="middle"
        />
      </Card>

      {/* 编辑角色模态框 */}
      <Modal
        title="编辑角色菜单"
        open={modalVisible}
        onOk={handleSave}
        onCancel={closeModal}
        confirmLoading={modalLoading}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          requiredMark={false}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="角色编码"
                rules={[]}
              >
                <Text code style={{ 
                  fontSize: 14, 
                  padding: '4px 11px', 
                  display: 'block', 
                  background: '#f5f5f5', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '6px' 
                }}>
                  {editingRole?.code}
                </Text>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="角色名称"
                rules={[]}
              >
                <Text style={{ 
                  fontSize: 14, 
                  padding: '4px 11px', 
                  display: 'block', 
                  background: '#f5f5f5', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '6px' 
                }}>
                  {editingRole?.name}
                </Text>
              </Form.Item>
            </Col>
          </Row>



          <Form.Item
            name="menus"
            label="选择菜单"
            rules={[{ required: true, message: '请至少选择一个菜单' }]}
          >
            <Transfer
              dataSource={menus
                .sort((a, b) => (a.order || 0) - (b.order || 0)) // 按后端提供的order字段排序
                .filter(menu => !menu.hidden) // 过滤隐藏菜单
                .map(menu => ({
                  key: menu.key,
                  title: menu.title,
                  description: menu.description,
                  icon: menu.icon,
                  category: menu.description.includes('/dashboard') ? 'dashboard' :
                           menu.description.includes('/tenant') ? 'tenant' :
                           menu.description.includes('/user') || menu.description.includes('/role') || menu.description.includes('/permission') ? 'user' :
                           menu.description.includes('/system') || menu.description.includes('/setting') ? 'system' :
                           menu.description.includes('/ticket') ? 'monitor' : 'other'
                }))}
              titles={['可选菜单', '已选菜单']}
              targetKeys={selectedMenus}
              onChange={(targetKeys) => {
                setSelectedMenus(targetKeys);
                form.setFieldsValue({ menus: targetKeys });
              }}
              render={(item) => (
                <div style={{ 
                  display: 'flex', 
                  flexDirection: 'column',
                  gap: 4,
                  padding: '4px 0'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{
                      width: 4,
                      height: 12,
                      background: MENU_GROUPS[item.category as keyof typeof MENU_GROUPS]?.color === 'blue' ? '#1890ff' :
                                 MENU_GROUPS[item.category as keyof typeof MENU_GROUPS]?.color === 'green' ? '#52c41a' :
                                 MENU_GROUPS[item.category as keyof typeof MENU_GROUPS]?.color === 'orange' ? '#fa8c16' :
                                 MENU_GROUPS[item.category as keyof typeof MENU_GROUPS]?.color === 'purple' ? '#722ed1' : '#ff4d4f',
                      borderRadius: 2
                    }} />
                    {item.icon && (
                      <span style={{ fontSize: 14, color: '#666' }}>
                        {/* 这里可以根据icon字符串渲染对应的图标 */}
                        📋
                      </span>
                    )}
                    <span style={{ fontWeight: 500, color: '#262626' }}>
                      {item.title}
                    </span>
                    <Tag 
                       color={MENU_GROUPS[item.category as keyof typeof MENU_GROUPS]?.color || 'default'}
                       style={{ fontSize: 11 }}
                     >
                       {MENU_GROUPS[item.category as keyof typeof MENU_GROUPS]?.label || item.category}
                     </Tag>
                  </div>
                  <Text type="secondary" style={{ fontSize: 12, marginLeft: 12 }}>
                    {item.description}
                  </Text>
                </div>
              )}
              showSearch
              filterOption={(inputValue, option) =>
                option.title.toLowerCase().includes(inputValue.toLowerCase()) ||
                option.description.toLowerCase().includes(inputValue.toLowerCase())
              }
              listStyle={{
                width: 300,
                height: 400,
              }}
              operations={['添加', '移除']}
              showSelectAll={false}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 角色详情模态框 */}
      <Modal
        title={
          <Space>
            <EyeOutlined />
            角色详情
          </Space>
        }
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
        bodyStyle={{ padding: '24px' }}
      >
        {detailRole && (
          <div>
            <Descriptions
              title="基本信息"
              bordered
              column={2}
              size="middle"
              labelStyle={{ 
                width: '120px',
                textAlign: 'right',
                fontWeight: 'bold',
                backgroundColor: '#fafafa'
              }}
              contentStyle={{
                textAlign: 'left',
                padding: '12px 16px'
              }}
              style={{ marginBottom: 32 }}
            >
              <Descriptions.Item label="角色名称" span={2}>
                <Space align="center">
                  <TeamOutlined style={{ color: '#1890ff', fontSize: '16px' }} />
                  <span style={{ fontWeight: 'bold', fontSize: '16px' }}>{detailRole.name}</span>
                  {detailRole.isBuiltin && <Tag color="gold">内置角色</Tag>}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="角色编码">
                <Text code style={{ fontSize: '14px' }}>{detailRole.code}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="角色状态">
                {detailRole.status === 'active' || detailRole.status === 1 ? 
                  <Tag color="green" style={{ fontSize: '12px', padding: '4px 8px' }}>启用</Tag> : 
                  <Tag color="red" style={{ fontSize: '12px', padding: '4px 8px' }}>禁用</Tag>
                }
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                <Text style={{ fontSize: '14px' }}>
                  {detailRole.createTime ? new Date(detailRole.createTime).toLocaleString('zh-CN') : '-'}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                <Text style={{ fontSize: '14px' }}>
                  {detailRole.updateTime ? new Date(detailRole.updateTime).toLocaleString('zh-CN') : '-'}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="描述" span={2}>
                <Text style={{ fontSize: '14px', color: detailRole.description ? '#262626' : '#8c8c8c' }}>
                  {detailRole.description || '暂无描述'}
                </Text>
              </Descriptions.Item>
            </Descriptions>

            <Divider orientation="left" orientationMargin="0" style={{ margin: '24px 0 16px 0' }}>
              <Text strong style={{ fontSize: '16px', color: '#262626' }}>菜单权限</Text>
            </Divider>
            
            <div style={{ 
              marginBottom: 16, 
              padding: '8px 12px',
              backgroundColor: '#f5f5f5',
              borderRadius: '6px',
              border: '1px solid #d9d9d9'
            }}>
              <Text strong style={{ fontSize: '14px', color: '#595959' }}>
                已分配菜单：{detailRole.permissions?.length || 0} 个
              </Text>
            </div>
            
            {detailRole.permissions && detailRole.permissions.length > 0 ? (
              <div style={{ 
                maxHeight: 280, 
                overflow: 'auto',
                padding: '16px',
                backgroundColor: '#fafafa',
                borderRadius: '6px',
                border: '1px solid #e8e8e8'
              }}>
                <Row gutter={[12, 12]} align="top">
                  {menus
                    .filter(menu => detailRole.permissions.includes(menu.key))
                    .map(menu => (
                      <Col key={menu.key} flex="none">
                        <Tag 
                          color="blue" 
                          style={{ 
                            fontSize: '13px', 
                            padding: '4px 12px',
                            borderRadius: '4px',
                            margin: 0
                          }}
                        >
                          {menu.title}
                        </Tag>
                      </Col>
                    ))
                  }
                </Row>
              </div>
            ) : (
              <div style={{
                textAlign: 'center',
                padding: '40px 20px',
                backgroundColor: '#fafafa',
                borderRadius: '6px',
                border: '1px solid #e8e8e8'
              }}>
                <Text type="secondary" style={{ fontSize: '14px' }}>暂无分配菜单</Text>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default PlatformPermissionsPage;